<?php
namespace app\admin\service;

use think\Cache;
use think\Model;
use think\Request;
use think\Db;
use app\model\Capital as CapitalModel;
use app\model\User as UserModel;
use app\model\TransferLog as TransferLogModel;
use app\lib\Alipay;

class Capital extends Model
{
    protected $mCapital;

    public function __construct()
    {
        parent::__construct();
        $this->mCapital = new CapitalModel();
    }

    /**
     * @auther zlq
     * @create_time 2020/5/21 22:32
     * @description 获取资金记录
     * @param $param
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getCapitalList($param)
    {
        $page_size = $param['page_size'];
        $select = [];
        if($param['user']){
            $select['a.dd_user_id'] = $param['user'];
        }
        if($param['capital_status']){
            $select['a.status'] = $param['capital_status'];
        }
        if($param['capital_type']){
            $select['a.type'] = $param['capital_type'];
        }
        if ($param['start_date']) {
            $date = date('Y-m-d H:i:s', strtotime($param['start_date']));
            $select['a.create_time'] = ['gt', $date];
        }
        if ($param['end_date']) {
            $date = date('Y-m-d H:i:s', strtotime($param['end_date']));
            $select['a.create_time'] = ['lt', $date];
        }
        if ($param['start_date'] && $param['end_date']) {
            $date1 = date('Y-m-d H:i:s', strtotime($param['start_date']));
            $date2 = date('Y-m-d H:i:s', strtotime($param['end_date']));
            $select['a.create_time'] = ['between', [$date1, $date2]];
        }
        $list = $this->mCapital
            ->alias('a')
            ->join('user b', 'a.dd_user_id = b.dd_user_id', 'left')
            ->field('a.*, b.capital')
            ->where($select)
            ->order('a.id desc')
            ->paginate($page_size, false, [
                'query' => Request::instance()->param(),
            ]);

        return $list;
    }



    /**
     * @auther zlq
     * @create_time 2020/5/21 22:32
     * @description 获取导出表格数据
     * @param $param
     * @param $type
     * @return array|bool|false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getCapitalListExcel($param, $type)
    {
        $select = [];
        switch ($type) {
            case 1:
                $ids = $param['ids'];
                $ids_array = array_filter(explode('-', $ids));
                if (empty($ids_array)) {
                    return [];
                }
                $select['a.id'] = ['in', $ids_array];
                return $this->mCapital
                    ->alias('a')
                    ->join('user b', 'a.dd_user_id = b.dd_user_id', 'left')
                    ->field('a.*, b.capital')
                    ->where($select)
                    ->order('a.id desc')
                    ->select();
                break;
            case 2:
                if($param['user']){
                    $select['a.dd_user_id'] = $param['user'];
                }
                if($param['capital_status']){
                    $select['a.status'] = $param['capital_status'];
                }
                if($param['capital_type']){
                    $select['a.type'] = $param['capital_type'];
                }
                return $this->mCapital
                    ->where($select)
                    ->alias('a')
                    ->join('user b', 'a.dd_user_id = b.dd_user_id', 'left')
                    ->field('a.*, b.capital')
                    ->order('a.id desc')
                    ->select();
                break;
            default:
                return [];
                break;
        }

    }

    /**
     * @auther zlq
     * @create_time 2020/5/23 10:27
     * @description 获取资金单用户列表
     * @return bool|false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getCapitalUserList()
    {
        $useModel = new UserModel();
        $list = $useModel
            ->field('dd_user_id, name')
            ->select();
        return $list;
    }

    /**
     * @auther zlq
     * @create_time 2020/5/23 10:44
     * @description 审核通过提现单信息
     * @param int $id 提现单ID
     * @param string $remark 备注
     * @param string $file 文件
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function auditCapitalPass($id = 0, $remark = "", $file = "")
    {
        if ($id < 1) {
            return -1;
        }
        $capital = $this->mCapital->where(['id' => $id])->find();
        if (empty($capital)) {
            return -2;
        }
        if (!($capital['type'] == 2 && $capital['status'] == 2)) {
            return -3;
        }
        // 获取提现用户信息
        $mUser = new UserModel();
        $capital_user = $mUser->where(['dd_user_id' => $capital['dd_user_id']])->find();
        if (empty($capital_user)) {
            return -4;
        }
        if (!($capital_user['account_user'] && $capital_user['account_code'])) {
            return -4;
        }
        $now_user = session('user_id');
        $now_user_name =  session('user_name');
        $now_time = date('Y-m-d H:i:s');
        if ($remark) {
            $tip = $now_user_name . '于' . $now_time . '审核通过提现,备注:' . $remark . ';';
        } else {
            $tip = $now_user_name . '于' . $now_time . '审核通过提现;';
        }
        // 这里同时进行支付宝转账的功能

        $alipay = new Alipay();
        $worker_name = $capital_user['account_user'];
        $worker_phone = $capital_user['account_code'];
        $amount = $capital['amount'];
        $out_biz_no = uniqid();
        $order_title = '工人任务单工资发放';
        $remark_alipay = '工人任务单工资发放';
        $data = [
            'out_biz_no' => $out_biz_no,
            'trans_amount' => $amount,
            'order_title' => $order_title,
            'worker_phone' => $worker_phone,
            'worker_name' => $worker_name,
            'remark' => $remark_alipay,
        ];
        // 加密
        Cache::set($worker_phone, md5($worker_phone.ALIPAY_CUSTOM_KEY),60);
        $alipay_res = $alipay->transferAccountToWorker($data);
        // 添加支付宝付款记录
        $transfer_log = [
            'code' => isset($alipay_res['data']['code']) ? $alipay_res['data']['code'] : '',
            'msg' => isset($alipay_res['data']['status']) ? $alipay_res['data']['status'] : '',
            'order_id' => isset($alipay_res['data']['order_id']) ? $alipay_res['data']['order_id'] : '',
            'out_biz_no' => isset($alipay_res['data']['out_biz_no']) ? $alipay_res['data']['out_biz_no'] : '',
            'pay_fund_order_id' => isset($alipay_res['data']['pay_fund_order_id']) ? $alipay_res['data']['pay_fund_order_id'] : '',
            'status' => isset($alipay_res['data']['status']) ? $alipay_res['data']['status'] : '',
            'trans_date' => isset($alipay_res['data']['trans_date']) ? $alipay_res['data']['trans_date'] : '',
            'trans_amount' => isset($alipay_res['data']['trans_amount']) ? $alipay_res['data']['trans_amount'] : '',
            'worker_phone' => isset($alipay_res['data']['worker_phone']) ? $alipay_res['data']['worker_phone'] : '',
            'worker_name' => isset($alipay_res['data']['worker_name']) ? $alipay_res['data']['worker_name'] : '',
            'origin' => json_encode($alipay_res),
        ];
        $mTransferLog = new TransferLogModel();
        if ($alipay_res['status'] == 0) {
            // 转账失败了
            $update_info = [
                'status' => 4,
                'account_user' => $capital_user['account_user'],
                'account_code' => $capital_user['account_code'],
                'alipay_code' => $out_biz_no,
                'update_time' => $now_time,
                'update_user' => $now_user,
                'update_file' => $file,
                'update_remark' => $remark,
                'status_remark' => $capital['status_remark'] . $tip,
                'remark' => '支付宝转账失败',
            ];
            // 修改用户资金，加上未提现成功的资金
            $capital_user_capital = sprintf('%.2f', $capital_user['capital'] + $capital['amount']);
            $update_capital_user = [
                'capital' => $capital_user_capital
            ];
            try {
                Db::startTrans();
                $res1 = $this->mCapital->where(['id' => $id])->update($update_info);
                $res2 = $mUser->where(['dd_user_id' => $capital['dd_user_id']])->update($update_capital_user);
                $res3 = $mTransferLog->insert($transfer_log);
                if ($res1 && $res2 && $res3) {
                    Db::commit();
                    return 2;
                } else {
                    Db::rollback();
                    return 0;
                }
            } catch (\Exception $exception) {
                Db::rollback();
                return 0;
            }
        } else {
            // 转账成功
            try {
                Db::startTrans();
                // 修改资金信息
                $update_info = [
                    'account_user' => $capital_user['account_user'],
                    'account_code' => $capital_user['account_code'],
                    'alipay_code' => $out_biz_no,
                    'status' => 3,
                    'update_time' => $now_time,
                    'update_user' => $now_user,
                    'update_file' => $file,
                    'update_remark' => $remark,
                    'status_remark' => $capital['status_remark'] . $tip
                ];
                $res1 = $this->mCapital->where(['id' => $id])->update($update_info);
                $res2 = $mTransferLog->insert($transfer_log);
                if ($res1 && $res2) {
                    Db::commit();
                    return 1;
                } else {
                    Db::rollback();
                    return 0;
                }
            } catch (\Exception $exception) {
                Db::rollback();
                return -1;
            }
        }

    }

    /**
     * @auther zlq
     * @create_time 2020/5/23 10:44
     * @description 审核退回提现
     * @param int $id 提现单ID
     * @param string $remark 备注
     * @param string $file 文件路径
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function auditCapitalRefuse($id = 0, $remark = "", $file = "")
    {
        if ($id < 1) {
            return -1;
        }
        $capital = $this->mCapital->where(['id' => $id])->find();
        if (empty($capital)) {
            return -2;
        }
        if (!($capital['type'] == 2 && $capital['status'] == 2)) {
            return -3;
        }
        $mUser = new UserModel();
        if (!$capital['dd_user_id']) {
            return -4;
        }
        // 获取提现用户信息
        $capital_user = $mUser->where(['dd_user_id' => $capital['dd_user_id']])->find();
        if (empty($capital_user)) {
            return -4;
        }
        $now_user = session('user_id');
        $now_user_name =  session('user_name');
        $now_time = date('Y-m-d H:i:s');
        if ($remark) {
            $tip = $now_user_name . '于' . $now_time . '审核退回提现,备注:' . $remark . ';';
        } else {
            $tip = $now_user_name . '于' . $now_time . '审核退回提现;';
        }
        $update_info = [
            'status' => 4,
            'update_time' => $now_time,
            'update_user' => $now_user,
            'update_file' => $file,
            'update_remark' => $remark,
            'status_remark' => $capital['status_remark'] . $tip
        ];
        // 修改用户资金，加上未提现成功的资金
        $capital_user_capital = sprintf('%.2f', $capital_user['capital'] + $capital['amount']);
        $update_capital_user = [
            'capital' => $capital_user_capital
        ];
        try {
            Db::startTrans();
            $res1 = $this->mCapital->where(['id' => $id])->update($update_info);
            $res2 = $mUser->where(['dd_user_id' => $capital['dd_user_id']])->update($update_capital_user);
            if ($res1 && $res2) {
                Db::commit();
                return 1;
            } else {
                Db::rollback();
                return 0;
            }
        } catch (\Exception $exception) {
            Db::rollback();
            return 0;
        }
    }
}